/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */

var folderRoot;
var rootFolder;
var folderId;
var folderLang = "fr";
	
function catchFoldersClick()
{
	$("#folders a").livequery('click', function(event){
		numPage = 1;
		$("#folders a").removeClass("folderSelected");
		
		params = getHash($(this).attr("href")).split("/");
		
		$(this).addClass("folderSelected");
		
		folderId = params[1];
		folderLang = params[0];
				
		loadFolderContent();
	});

	$('a.mediaModal').livequery('click', function(){
		var href = getHash(this.href);
		
		if($(this).hasClass("deleteImg") == false)
		{
			href = href + "/"+folderLang+"/"+folderId;
		}
		
		showModal("?module=backoffice&action=AjaxController&href='"+href+"'&mce=1");
		return false;
	});
}

function showMediaIcon()
{
	if($("#foldersTitle a").hasClass("folderSelected") == false)
	{
		$("#boSearch a.addMedia").show();
		$("#boSearch a.deleteFolder").show();
	}
	else
	{
		$("#boSearch a.addMedia").hide();
		$("#boSearch a.deleteFolder").hide();
	}
	
	$("#boSearch a.addFolder").show();
}

function loadFolderContent(selectedId)
{
	$.ajax({
		url: "?module=medias&action=block_MceObjectFolderContent",
		data: "folderId="+folderId+"&folderLang="+folderLang+"&rootFolder="+rootFolder,
		beforeSend: function()
		{
			$("#preload").show();
			$("#pagination img").unbind();
			$("#pagination select").unbind();
		},
		success: function(response)
		{
	 		$("#content").html(response);
			catchImageClick();
			showMediaIcon();
			$("#preload").hide();
			if(selectedId != null)
			{
				folder = "#"+folderLang+"_"+selectedId;
				$(folder).children(".image").addClass("imageSelected");
				$(folder).children(".imageTitle").children(".imageTitleText").addClass("imageTitleSelected");
				$("#folder_"+folderId+" a").addClass("folderSelected");
			}
		}
	});	
}

function loadFolders(folderSelectId, folderSelectLang)
{
	$.ajax({
		url: "?module=medias&action=block_MceObjectFolders",
		success: function(response)
		{
			$("#leftCol").html(response);
			if($("#folder_"+folderSelectId).length)
			{
				folderId = folderSelectId;
				folderLang = folderSelectLang;
				$("#folder_"+folderSelectId).children("a").addClass("folderSelected");
			}
			else
			{
				folderId = folderRoot;
				$("#foldersTitle a").addClass("folderSelected");
			}
			
			loadFolderContent();
		}
	});
}

function save()
{
    var objSelected = $("#objSelected").val();
    var urlObj = $("#url").val();
    var objValue = $("#objValue").val();
    var obj = folderLang+'/'+folderId+'/'+objSelected;

    window.opener.saveObj(obj, objValue, urlObj);
	window.close();
}


function moveSelection(num)
{
	$(".image").removeClass("imageSelected");
	$(".imageTitleText").removeClass("imageTitleSelected");
	$("."+num).children(".image").addClass("imageSelected");
	$("."+num).children(".imageTitle").children(".imageTitleText").addClass("imageTitleSelected");
	params = $("."+num).attr("id").split("_");
	loadObjectDetails(params[1], params[0], params[2]);
}

function catchImageClick()
{
    $(".objContainer").click(function(event){
        params = $(this).attr("class").split(" ");
        moveSelection(params[1]);
    });
}

function loadObjectDetails(docId, docLang, rootFolder)
{
	$.ajax({
		async: false,
		url: "?module=medias&action=block_MceObjectDetail",
		data: "docId="+docId+"&docLang="+docLang+"&rootFolder="+rootFolder,
		success: function(response)
		{
	 		$("#mediaDetail").html(response);
	 		$("#mediaTitle a.saveImg").click(function(){
	 			save();
	 		});
	 		
	 		$("#mediaTitle a.deleteImg").attr({
	 			href: "index.php#href=medias/deleteFolder/"+docLang+"/"+docId
	 		});
			
	 		if ($("#mediaDetail").height() == 245) {
				$("#mediaOptionnal").show();
				enableColorPicker();
			}
		}
	});	
}


function refreshRightCol(fileName, text)
{
	//loadMediaDetails($("#pictureId").text(), $("#pictureLang").text());
	check = $("#sizes").children("[value="+fileName+"]").length;
	
	if(check >= 1)
	{
		$("#sizes").children("[value="+fileName+"]").attr("selected", "selected");
	}
	else
	{
		$("#sizes option").removeAttr("selected");
		$("#sizes").append('<option value="'+fileName+'" selected="selected">' + text + '</option>');
	}
}

function loadPictureParams(dom, n)
{
	srcAttr = dom.getAttrib(n, 'src');
	alt = dom.getAttrib(n, 'alt');
	title = dom.getAttrib(n, 'title');
	style = dom.getAttrib(n, 'style');
	classe = dom.getAttrib(n, 'class');
	styles = style.split(";");
	
	source = src.split("/");
	name = source[source.length-1];
	attrs = name.split("?");
	picName = attrs[0];
	
	$("#sizes").children("[@value="+picName+"]").attr("selected", "selected");	

	for( var i in styles)
	{
		params = styles[i].split(": ");
		paramName = $.trim(params[0]);
		paramValue = $.trim(params[1]);

		switch(paramName)
		{
			case("float"):
				$("#formAlign").children("[@value="+paramValue+"]").attr("selected", "selected");
			break;
			
			case("margin"):
				margins = paramValue.split(" ");
				
				$("#formMarginTop").attr("value", margins[0].replace("px", ""));
				$("#formMarginRight").attr("value", margins[1].replace("px", ""));
				$("#formMarginBottom").attr("value", margins[2].replace("px", ""));
				$("#formMarginLeft").attr("value", margins[3].replace("px", ""));
			break;
			
			case("border"):
				borderParams = paramValue.split(" ");
				
				$("#formBorderWeight").attr("value", borderParams[0].replace("px", ""));
				$("#selectorBg").css("background-color", borderParams[2]);
				$("#hexColor").text(borderParams[2]);
			break;
		}
	}
	
	$("#formAlt").val(alt);
	$("#formTitle").val(title);
	$("#formClass").val(classe);
}

function initBrowser()
{
    var ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(), hash = window.location.hash.replace(/^.*#/, "");

    if(n != null && n.nodeName == 'IMG')
    {        
        src = dom.getAttrib(n, 'src');
        id = dom.getAttrib(n, 'id');
        params = src.split('/');
        pictureParams = id.split('_');
        tabLength = params.length;
        folderId = params[tabLength-3];
        folderLang = params[tabLength-2];

        window.location.hash = folderLang.toUpperCase()+"/"+folderId;
        loadFolderContent(pictureParams[1]);
        loadMediaDetails(pictureParams[1], params[tabLength-2]);
        loadPictureParams(dom, n);
    }
    else
    {        
        if(hash != "")
        {
            params = hash.split("/");
            folderId = params[1];
            folderLang = params[0].toLowerCase();
            $("#folder_"+folderId+" a").addClass("folderSelected");
            (params[2]) ? loadFolderContent(params[2]) : loadFolderContent();
        }
        else
        {
            folderId = folderRoot;
            $("#foldersTitle a").addClass("folderSelected");
        }
    }

    showMediaIcon();
}

/**
 * Ouvre une popup centrée
 * @param {String} windowURL
 * @param {String} windowName
 * @param {Integer} windowWidth
 * @param {Integer} windowHeight
 * @param {Boolean} hasScrollbars
 * @param {Boolean} isResizable
 * @param {Boolean} hasMenubar
 * @param {Boolean} hasToolbar
 * @param {Boolean} hasAddressbar
 * @param {Boolean} hasStatusbar
 * @param {Boolean} isFullscreen
 */
function centeredPopup(windowURL, windowName, windowWidth, windowHeight, hasScrollbars, isResizable, hasMenubar, hasToolbar, hasAddressbar, hasStatusbar, isFullscreen) 
{
  var windowLeft = (screen.width - windowWidth) / 2;
  var windowTop = (screen.height - windowHeight) / 2;
  var windowProperties = 'height=' + windowHeight + ',width=' + windowWidth + ',top=' + windowTop + ',left=' + windowLeft + ',scrollbars=yes' + ',resizable=' + isResizable + ',menubar=' + hasMenubar + ',toolbar=' + hasToolbar + ',location=' + hasAddressbar + ',statusbar=' + hasStatusbar + ',fullscreen=' + isFullscreen + '';
  var objwindow = window.open(windowURL, windowName, windowProperties)
    if (parseInt(navigator.appVersion) >= 4) {
      objwindow.window.focus();
    }
}

function liveQueryTooltips()
{
	$('.toolTip, input, select').livequery(function()
	{
		$(this).tooltip(
		{ 
		    track: true, 
		    delay: 500, 
		    showURL: false, 
		    fixPNG: true, 
		    showBody: " - ", 
		    extraClass: "fancy", 
		    top: -5, 
		    left: 5
		})
	});
}

function showModal(href)
{
	$.nyroModalManual({
		url: href,
		minHeight: 100,
		minWidth: 100,
		modal: true,
		bgColor: '#F2F1EE',
		showBackground: function(elts, settings, callback){
			elts.bg.css("opacity", "0.5");
			callback();
		},
		hideBackground: function(elts, settings, callback){
			elts.bg.hide();
			callback();
		},
		showLoading: function(elts, settings, callback)
		{
			elts.loading.hide();
			callback();
		},			
		showContent: function(elts, settings, callback) {
		  elts.contentWrapper
		    .css({ // Reset the CSS at the start position
		      marginTop: (-100/2 + settings.marginScrollTop)+'px',
		      marginLeft: (-100/2 + settings.marginScrollLeft)+'px',
		      height: '100px',
		      width: '100px',
		      opacity: 0
		    })
		    .show()
		    .css({ // Set the width
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
		    });
			callback();				
		},
		endShowContent: function(elts, settings){
			$("#submitButton").focus();

			var link = $("#formsuccess").html();
			if (link != null && link != "") {
				var tabLink = link.split("/");
				$.nyroModalRemove();
				loadFolders(tabLink[tabLink.length-1], tabLink[tabLink.length-2]);
			}	
		},
		hideContent: function(elts, settings, callback){
			elts.contentWrapper.hide();
			callback();
		},
		showTransition: function(elts, settings, callback){
			elts.loading
			.css({
				marginTop: elts.contentWrapper.css('marginTop'),
				marginLeft: elts.contentWrapper.css('marginLeft'),
				height: elts.contentWrapper.css('height'),
				width: elts.contentWrapper.css('width'),
				opacity: 1
			})
			.show();
			elts.contentWrapper.hide();
			callback();
		},
		hideTransition: function(elts, settings, callback){
			elts.loading.hide();
			elts.contentWrapper
			.css({
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
			}).show();
			callback();	
		}
	});
}

function getHash(href)
{
	return href.replace(/^.*#/, '');
}

/******************************************SLIDER MENU**************************************************/

function slidingMenuUpDown()
{
    $('.slideMenu').css('top', '0px');
    if(($('#leftCol').height()-119) < ($('#slideMenuContainer').height()))
    {
        $('.menuSlidingUpDown').show();

        $('#menuDown').mousedown(function()
        {
            t = parseInt($('.slideMenu').css('top').replace('px', ''));
            diff = ($('#leftCol').height()-119) - $('#slideMenuContainer').height();
            $(this).addClass('menuSlidingUpDownClick');
            if(t > diff)
            {
                $('.slideMenu').css('top', t-16+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });

        $('#menuUp').mousedown(function()
        {
            $(this).addClass('menuSlidingUpDownClick');
            t = parseInt($('.slideMenu').css('top').replace('px', ''));
            if(t < 0)
            {
                $('.slideMenu').css('top', (t+16)+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });
    }
    else
    {
        $('.menuSlidingUpDown').hide();
    }
}

$(document).ready(function(){
        slidingMenuUpDown();
        $(window).resize(function(){slidingMenuUpDown()});
	liveQueryTooltips();
	catchFoldersClick();	
	initBrowser();	
});